import { defineComponent, Fragment, reactive, toRefs, getCurrentInstance } from 'vue'
import PropTypes from 'ant-design-vue/es/_util/vue-types'
import { pattern } from '@/utils/validate'

export const smsProps = {
  validStatus: PropTypes.bool,
  mobile: PropTypes.string
}

const smsCode = defineComponent({
  name: 'sms-code',
  props: smsProps,
  emits: ['codeSuccess'],
  setup(props, context) {
    const state = reactive({
      smsSendBtn: false,
      time: 60
    })

    // 获取路由、ref当前组件实例对象
    const { ctx } = getCurrentInstance()

    const getCaptcha = (e) => {
      e.preventDefault()

      if (pattern.mobile.test(props.mobile)) {
        state.smsSendBtn = true
        const interval = window.setInterval(() => {
          if (state.time-- <= 0) {
            state.time = 60
            state.smsSendBtn = false
            window.clearInterval(interval)
          }
        }, 1000)

        const hide = ctx.$message.loading('验证码发送中..', 0)

        setTimeout(hide, 1000)

        context.emit('codeSuccess')
      } else {
        ctx.$notification['error']({
          message: '提示',
          description: '请输入正确的手机号',
          duration: 4
        })
      }
    }

    return {
      ...toRefs(state),
      getCaptcha
    }
  },
  render() {
    const {
      getCaptcha,
      smsSendBtn,
      time
    } = this

    return (
      <Fragment>
        <a-button
          tabindex="-1"
          disabled={smsSendBtn}
          onClick={getCaptcha}
          size="large"
        >
          {!smsSendBtn && '获取验证码' || (time + ' s')}
        </a-button>
      </Fragment>
    )
  },
})

export default smsCode
